import React, { useState } from "react";
import { Table } from 'antd';

export default function Option1() {
  const columns = [{
    title: 'Id',
    dataIndex: 'key', // dataIndex的属性名和data中的属性名是一一对应的关系
  }, {
    title: 'Name',
    dataIndex: 'name',
    render: text => <a href="#">{text}</a>,
  }, {
    title: 'Age',
    dataIndex: 'age',
  }, {
    title: 'Address',
    dataIndex: 'address',
  }];

  const data = [{
    key: '1',
    name: 'John Brown',
    age: 32,
    address: 'New York No. 1 Lake Park',
  }, {
    key: '2',
    name: 'Jim Green',
    age: 42,
    address: 'London No. 1 Lake Park',
  }, {
    key: '3',
    name: 'Joe Black',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
  }, {
    key: '4',
    name: 'Disabled User',
    age: 99,
    address: 'Sidney No. 1 Lake Park',
  }];
  // 可选框
  const [selectedRowKeys, setSelectedRowKeys] = useState([]) // 被选中数据组成的数组
  // 点击可选框时触发
  const onSelectedRowKeysChange = (selectedRowKeys) => {
    setSelectedRowKeys(selectedRowKeys)
    console.log(selectedRowKeys)
  }
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectedRowKeysChange // 选中项发生变化时的回调
  };
  // 点击可选框右侧的行时触发
  const selectRow = (record) => {
    const selectedRowKeysed = [...selectedRowKeys];
    if (selectedRowKeysed.indexOf(record.key) >= 0) {
      selectedRowKeysed.splice(selectedRowKeysed.indexOf(record.key), 1);
    } else {
      selectedRowKeysed.push(record.key);
    }
    setSelectedRowKeys(selectedRowKeysed)
    console.log(selectedRowKeysed);
  }
  return (
    <div style={{ padding: 20 }}>
      <h3>表格</h3>
      <Table
        rowSelection={rowSelection} // 显示左侧可选框
        bordered // 边框线
        pagination={false} // 去掉分页
        columns={columns} // 表头
        dataSource={data} // 表数据
        align='center'
        onRow={(record) => ({
          onClick: () => {
            selectRow(record)
          }
        })}
      />
    </div>
  )
}